<template>
  <el-container style="height:100%">
    <el-aside width="250px">
      <div style="height:100%;position:relative">
        <el-input placeholder="搜索姓名/医保卡号" prefix-icon="el-icon-search" v-model="searchText" @change="search"></el-input>
        <div style="position:absolute;top:40px;bottom:0px;width:100%;overflow-y:auto">
          <div
            :class="['item', item.recordState == 'save' ? 'item-noresult' : '' ]"
            v-for="(item,index) in showPatients"
            :key="index"
            @click="showDetail(item.recordDocId)"
          >
            <div>
              <span>{{ item.patientName }}({{ item.age }}岁)</span>
              <span class="span-right">{{ item.medicareId }}</span>
            </div>
            <div class="divButtom">
              <span>就诊次数： {{ item.treatCount }}</span>
              <span class="span-right">{{ item.visitDate }} {{ item.visitTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-aside>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="18">
          <el-card class="box-card" style="height: 250px;overflow-y:auto">
            <table style="width:100%" v-if="chosenRecord">
              <tr>
                <td style="width:100px">姓名：{{ chosenRecord.patientInfo.patientName.value }}</td>
                <td>性别：{{ chosenRecord.patientInfo.sex.value }}</td>
                <td>年龄：{{ chosenRecord.patientInfo.age.value }}</td>
                <td>医保卡号：{{ chosenRecord.patientInfo.medicareId.value }}</td>
                <td>手机号：{{ chosenRecord.patientInfo.telephone.value }}</td>
              </tr>
              <tr>
                <td>心率：{{ chosenRecord.patientInfo.heartRate.value }}pm</td>
                <td>体温：{{ chosenRecord.patientInfo.temperature.value }}℃</td>
                <td>身高：{{ chosenRecord.patientInfo.height.value }}cm</td>
                <td>体重：{{ chosenRecord.patientInfo.weight.value }}kg</td>
                <td>血压：{{ chosenRecord.patientInfo.sbp.value }}/{{ chosenRecord.patientInfo.dbp.value }} mmHg</td>
              </tr>
              <tr>
                <td>主诉：</td>
                <td colspan="4">
                  <p v-html="parsedChiefComplaint"></p>
                </td>
              </tr>
              <tr>
                <td>现病史：</td>
                <td colspan="4">
                  <p v-html="parsedHPI"></p>
                </td>
              </tr>
              <tr>
                <td>既往史：</td>
                <td colspan="4">
                  <p v-html="parsedPastHistory"></p>
                </td>
              </tr>
              <tr>
                <td>体格检查：</td>
                <td colspan="4">
                  <p v-html="parsedPE"></p>
                </td>
              </tr>
              <tr>
                <td>检查检验：</td>
                <td colspan="4">
                  <p v-html="parsedCheckout"></p>
                </td>
              </tr>
              <tr>
                <td>诊断：</td>
                <td colspan="4">
                  <p v-html="parsedDiagnosis"></p>
                </td>
              </tr>
            </table>
          </el-card>
        </el-col>
        <el-col :span="6">
          <div style="background-color: white;text-align:center;height:250px;">
            <div style="background-color: #606f87;color:white;padding: 10px;">
              <span>
                <el-date-picker class="myDate" style="width:150px"
                  v-model="date"
                  align="right"
                  type="date"
                  :clearable="false"
                  value-format="yyyy-MM-dd"
                  @change="initData">
                </el-date-picker>
              </span>
            </div>
            <div style="padding: 20px 0 2px 0">
              <span style="font-size: xx-large;color: #36a9ff;">{{ confirmed }}/{{ dailyAll }}</span>
              <p style="font-size: medium;color: #b5b5b5">确诊/问诊</p>
              <p style="font-size: xx-small;">平均问诊时间：{{ AverageTime }}min</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <div style="background-color: white;">
            <div style="background-color: #606f87;color:white;padding: 10px;">
              <span>疾病相关数据分析</span>
              <el-dropdown style="float: right;color:white;">
                <span class="el-dropdown-link">
                  当日
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>当日</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div ref="myChart" style="width:100%; height:300px">
            </div>
          </div>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/utils'

import { mapGetters } from 'vuex'
import { dailyPatients, sexRate } from '@/api/patientInfo'
import { getRecordsByIds } from '@/api/record'
import { parseChiefComplaint, parseHPI, parsePastHistory, parsePE, parseCheckout, parseDiagnosis } from '@/utils/index'
import moment from 'moment'
import _ from 'lodash'

export default {
  name: "Dashboard",
  data() {
    return {
      // date: moment().format('YYYY-MM-DD'),
      date: '2019-04-02',
      chosenRecord: null,
      searchText: "",
      dialogVisible: false,
      dailyPatients: [],
      showPatients: [],
      chart: null
    }
  },
  watch: {
    // searchText(newVal, oldVal) {
    //   _.debounce(this.search, 500)()
    // }
  },
  methods: {
    parseChiefComplaint,
    parseHPI,
    parsePastHistory,
    parsePE,
    parseCheckout,
    parseDiagnosis,
    initChart() {
      sexRate(this.date).then(res => {
        let diseaseData = new Set(), manData = [], womanData = []
        res.data.forEach(e => {
          diseaseData.add(e.diseaseName)
          if (e.sex == '男') {
            manData.push(e.num)
          }
          if (e.sex == '女') {
            womanData.push(e.num)
          }
        })
        this.chart.setOption({
          xAxis: [{
            data: Array.from(diseaseData),
          }],
          series: [
            {
              name: "男",
              data: manData
            },
            {
              name: "女",
              data: womanData
            }
          ]
        })
      })
    },
    search() {
      if (this.searchText) {
        this.showPatients = this.dailyPatients.filter(e => {
          if (e.patientName.includes(this.searchText) || e.medicareId.includes(this.searchText)) {
            return true
          } else {
            return false
          }
        })
      } else {
        this.showPatients = this.dailyPatients
      }
    },
    showDetail(recordId) {
      getRecordsByIds([recordId]).then(res => {
        this.chosenRecord = res.data[0]
      })
    },
    initData() {
      this.searchText = ''
      dailyPatients(this.date).then(res => {
        this.dailyPatients = res.data
        this.showPatients = res.data
      })
      this.initChart()
    }
  },
  computed: {
    ...mapGetters([
      'dictIndex',
    ]),
    confirmed() {
      return this.dailyPatients.filter(e => e.recordState == 'confirm').length
    },
    dailyAll() {
      return this.dailyPatients.length
    },
    AverageTime() {
      if (this.dailyPatients.length > 0) {
        let confirm = this.dailyPatients.filter(e => e.recordState == 'confirm')
        if (confirm.length > 0) {
          return parseInt(_.mean(confirm.map(e => {
            return moment(e.confirmTime, 'hh:mm:ss').diff(moment(e.visitTime, 'hh:mm:ss'),'minutes')
          })))
        } else {
          return '0'
        }
      } else {
        return '0'
      }
    },
    parsedChiefComplaint() {
      if (this.chosenRecord) {
        return parseChiefComplaint(this.chosenRecord.chiefComplaint, this.dictIndex)
      } else {
        return ''
      }
    },
    parsedHPI() {
      if (this.chosenRecord) {
        return parseHPI(this.chosenRecord.HPI, this.dictIndex)
      } else {
        return ''
      }
    },
    parsedPastHistory() {
      if (this.chosenRecord) {
        return parsePastHistory(this.chosenRecord.pastHistory, this.dictIndex)
      } else {
        return ''
      }
    },
    parsedPE() {
      if (this.chosenRecord) {
        return parsePE(this.chosenRecord.PE)
      } else {
        return ''
      }
    },
    parsedCheckout() {
      if (this.chosenRecord) {
        return parseCheckout(this.chosenRecord)
      } else {
        return ''
      }
    },
    parsedDiagnosis() {
      if (this.chosenRecord) {
        return parseDiagnosis(this.chosenRecord.diagnosis)
      } else {
        return ''
      }
    }
  },
  mounted() {
    // 默认拉取今日
    this.$store.dispatch('getTodayPatients', false).then(res => {
      this.dailyPatients = res
      this.showPatients = res
    })
    // 男女比例图表数据获取
    this.chart = echarts.init(this.$refs.myChart)
    this.chart.setOption({
      toolbox: {
        show: true,
        feature: {
          saveAsImage: {
            show: true,
            excludeComponents: ["toolbox"],
            pixelRatio: 2
          }
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      legend: {
        data: ["男", "女"]
      },
      grid: {
        top: 30,
        left: '2%',
        right: '2%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [{
        type: "category",
        data: [],
        axisTick: {
          alignWithLabel: true
        }
      }],
      yAxis: [{
        type: 'value',
        axisTick: {
          show: false
        }
      }],
      series: [
        {
          name: "男",
          type: "bar",
          stack: "总量",
          label: {
            normal: {
              show: true,
              position: "insideRight"
            }
          },
          data: []
        },
        {
          name: "女",
          type: "bar",
          stack: "总量",
          label: {
            normal: {
              show: true,
              position: "insideRight"
            }
          },
          data: []
        }
      ]
    })
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  .myDate > .el-input__inner {
    background-color: #606f87;
    border: 1px solid #606f87;
    color: #FFF;
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .item {
    color: #54657e;
    height: 60px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    cursor: pointer;
    .divButtom {
      font-size: smaller;
    }
    div {
      padding: 3px 15px;
      .span-right {
        float: right;
      }
    }
  }
  .item:hover {
    background-color: #ebf6ff;
  }
  .item:active {
    background-color: #36a9ff;
  }
  .item-noresult {
    background-color: #ffedeb;
  }
  .el-main {
    background-color: #d5dce5;
  }
  .el-row {
    margin-bottom: 20px;
  }
</style>
